package com.pig.controller.order;

import com.alibaba.dubbo.config.annotation.Reference;
import com.pig.pojo.addr.Addr;
import com.pig.pojo.order.Order;
import com.pig.pojo.order.OrderItem;
import com.pig.pojo.user.User;
import com.pig.service.cart.DubboCartService;
import com.pig.service.order.DubboOrderService;
import com.pig.util.SysResult;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.UUID;

@RestController
public class OrderController {


    @Reference(check = false)
    private DubboOrderService orderService;
    @Reference(check = false)
    private DubboCartService cartService;



    @RequestMapping("/order/showAddr")
    public SysResult showAddr(HttpServletResponse response){
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Cache-Control","no-cache");
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        Integer userId= Math.toIntExact(user.getId());
        /*Integer userId=77;//暂时写死，模拟数据*/
        List<Addr> addrList=orderService.findUserAddr(userId);
        return SysResult.success(addrList);
    }

    @RequestMapping("/order/saveOrder")
    public SysResult saveOrder(Order order, HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Cache-Control","no-cache");

        User user = (User) SecurityUtils.getSubject().getPrincipal();
        Integer userId= Math.toIntExact(user.getId());
        //Integer userId =77;//模拟用户数据
        order.setUserId(userId);
        String orderId = ""+ UUID.randomUUID();
        order.setOrderId(orderId);
        /*根据userId拿到购物车表的商品ID和商品NUM*/
        List<OrderItem> userItems = cartService.findCartUserItems(userId);
        /*根据orderID写入商品ID和商品NUM*/
        orderService.insertOrderItemByOrderId(userItems,orderId);
        /*根据userId删除购物车表中数据*/
        cartService.deleteCartByUserId(userId);
        /*存入订单*/
        orderService.savaOrder(order);

        System.out.println(order);
        return SysResult.success(order);
    }








}
